package customerEnter.Frame.Thread.impl;

import java.lang.reflect.Method;
import java.util.List;

import customerEnter.Frame.Annotation.FrameDataSourceController;
import customerEnter.Frame.AnnotationExecute.AnnotationExecute;
import customerEnter.Frame.Enum.DataSourceControllerEnum;
import customerEnter.Frame.JDBCDao.JdbcTemplate.RandomDataSource;
import customerEnter.Frame.JDBCDao.util.DaoFrameConntroller;
import customerEnter.Frame.Thread.StackTraceElements;
import customerEnter.Frame.Thread.interfaces.FrameReadWriteInit;
import customerEnter.Frame.Utils.Log4j;
import customerEnter.tool.WhetherToEmpty;

/**
 * 
 * 类描述： 文件掃描
 * 
 * 类名称：FrameReadWriteInitImpl
 * 
 * 创建人：dy
 * 
 * 创建时间：2017-8-29 上午10:56:22
 * 
 */
public class FrameReadWriteInitImpl implements FrameReadWriteInit {

	public void InitDataSourceRW(List<StackTraceElements> stackTraceElements) {
		FrameDataSourceController frameDataSourceController = null;
		for (StackTraceElements stack : stackTraceElements) {
			String className = stack.getClassName();
			String MethodName = stack.getMethodName();
			String keyName = stack.getClassName() + "." + stack.getMethodName();
			frameDataSourceController = DaoFrameConntroller.getDataSourceRW().get(keyName);
			if (WhetherToEmpty.ObjectWhetherToEmpty(frameDataSourceController)) {
				try {
					readWithController(className, MethodName, keyName);
				} catch (ClassNotFoundException e) {
					Log4j.Log4JOutError("初始化類失敗：" + e.getMessage());
				}
			} else {
				setDataSourceController(frameDataSourceController);
			}
		}

		// RandomDataSource.setDataSourceController(frameDataSourceController.sourceController());
	}

	public void readWithController(String className, String MethodName, String keyName) throws ClassNotFoundException {
		Class<?> class1 = Class.forName(className);
		String methodName = MethodName;
		Method method = AnnotationExecute.getThisMethod(class1, methodName);
		FrameDataSourceController frameDataSourceController = method.getAnnotation(FrameDataSourceController.class);
		DaoFrameConntroller.getDataSourceRW().put(keyName, frameDataSourceController);
		setDataSourceController(frameDataSourceController);
	}

	public void setDataSourceController(FrameDataSourceController frameDataSourceController) {
		if (!WhetherToEmpty.ObjectWhetherToEmpty(frameDataSourceController)) {
			// 如果設置了讀寫分離註解 就以讀寫分離註解為主
			RandomDataSource.setDataSourceController(frameDataSourceController.sourceController());
		} else {
			// 否則就以默認為主
			RandomDataSource.setDataSourceController(DataSourceControllerEnum.dataSource_read);
		}
	}
}
